package com.zjlanyun.eplus.view.form;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.jb.barcode.BarcodeManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.aihook.alertview.library.AlertView;
import com.aihook.alertview.library.OnItemClickListener;
import com.aihook.tableview.lib.TableDataAdapter;
import com.aihook.tableview.lib.TableFixHeaders;
import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.utils.KeyboardUtils;
import com.blankj.utilcode.utils.TimeUtils;
import com.blankj.utilcode.utils.ToastUtils;
import com.yanzhenjie.nohttp.rest.Response;
import com.zjlanyun.eplus.R;
import com.zjlanyun.eplus.greendao.DBHelper;
import com.zjlanyun.eplus.greendao.IrActWindow;
import com.zjlanyun.eplus.greendao.IrModelAccess;
import com.zjlanyun.eplus.greendao.IrModelAccessDao;
import com.zjlanyun.eplus.greendao.IrModelFields;
import com.zjlanyun.eplus.greendao.IrModelFieldsDao;
import com.zjlanyun.eplus.network.WebApi;
import com.zjlanyun.eplus.nohttp.HttpRequest;
import com.zjlanyun.eplus.nohttp.SimpleHttpListener;
import com.zjlanyun.eplus.utils.ButtonUtils;
import com.zjlanyun.eplus.utils.DatePickerDialogUtil;
import com.zjlanyun.eplus.utils.DateTimePickerDialogUtil;
import com.zjlanyun.eplus.utils.SPData;
import com.zjlanyun.eplus.utils.SoundManager;
import com.zjlanyun.eplus.utils.StringUtils;
import com.zjlanyun.eplus.view.BaseActivity;
import com.zjlanyun.eplus.view.CaptureActivity;

import org.greenrobot.greendao.query.QueryBuilder;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

public class FormActivity extends BaseActivity {

    private Intent intent;

    private IrModelFields irModelFieldsOne2Many = null;
    private List<IrModelFields> irModelFieldsOne2ManyList = null;
    private IrModelAccess irModelAccessOne2Many = null; //one2many模型权限
    private IrModelFields irModelFieldsOne2ManyKey; //one2many主键字段
    private ArrayList<String> entryDeleteItems; //表体删除内容的主键值
    private IrActWindow irActWindow;
    private long act_id = 0;//窗口ID
    private long model_id = 0; //模型ID
    private List<IrModelFields> irModelFieldsList; //字段list，不含one2many
    private HashMap<Long, IrModelFields> fieldsMap; //字段map，初始化好的字段
    private TableDataAdapter tableDataAdapter; //表格适配器
    private ArrayList<ArrayList<String>> tableListData; //表格数据
    private BarcodeManager scanManager;
    private boolean isPDA = false;
    private long curFieldId = 0; //当前扫描字段ID
    private ArrayList<HashMap<String, Object>> scanHeaderLog; //表头扫描记录
    private ArrayList<HashMap<String, Object>> scanBodyLog; //表体扫描记录
    private HashMap<String, Object> headerShowMap; //表头显示的数据
    private List<HashMap<String, Object>> mList; //表体显示的数据
    private List<HashMap<String, Object>> bodyList; //表体提交的数据
    private HashMap<Long, Object> itemWidget; //字段ID对应的控件
    private int curRow = -1; //当前行号
    private IrModelAccess irModelAccess; //模型权限
    private HashMap<Long, String[]> many2oneListMap; //供点击选择的数据
    private HashMap<Long, Integer> selectList; //用于保存关联字段选择之后保存的值位置
    private HashMap<Long, ArrayList<HashMap<String, Object>>> many2oneList; //保存提示的数据，通过提示数据可以显示在其他地方
    private boolean originList = false;
    private HashMap<Long, Many2One> many2oneHashMap;//保存many2one请求的列表实例

    private HashMap<Long, ArrayList<String>> many2oneMoreListMap; //用于获取more之后显示的内容
    private LayoutInflater layoutInflater;
    private Dialog dialog;
    private HashMap<Long, HashMap<String, HashMap<String, Object>>> changeMap; //用于关联的改变字段
    private HashMap<Long, Integer> changeSelectList; //用于保存关联字段选择之后保存的值位置
    private HashMap<Long, ArrayList<HashMap<String, Object>>> many2oneMoreList; //保存many2one字段获取更多数据
    private HashMap<String, Object> bodyItem; //表体临时值
    private HashMap<String, Object> headerItem; //表头临时值
    private ArrayList<String> bodyUpdateList; //表体有更新的数据key
    private SoundManager soundManager;
    private boolean notSave = false; //未保存

    private HashMap<Long, InitMany2One> many2oneFieldHashMap; //保存many2one初始化的对象
    private HashMap<Long, Object> many2oneDefValue; //保存many2one默认值
    private HashMap<Long, Boolean> many2oneOriginMore; //记录many2one字段是否从更多列表点击进来的

    private boolean isRequest = false; //是否正在请求中
    private boolean isTextChanged = false; //有文字改变监听
    private boolean isScaning = false; //正在扫描中
    private boolean isClickBody = false; //是否点击表体信息
    private boolean isCheck = false; //单据是否已经审核

    public final static int REQUESTCODE_CAMERA = 1;
    public final static int CHOICEBILL = 2;

    @Bind(R.id.ll_main) LinearLayout ll_main; //表体字段添加区域
    @Bind(R.id.ll_wrap) LinearLayout ll_wrap; //表头字段添加区域
    @Bind(R.id.sv_wrap) ScrollView sv_wrap; //表头字段添加区域
    @Bind(R.id.btn_1) Button btn_1;
    @Bind(R.id.btn_2) Button btn_2;
    @Bind(R.id.btn_3) Button btn_3;
    @Bind(R.id.btn_4) Button btn_4;
    @Bind(R.id.table) TableFixHeaders table;
    @Bind(R.id.ib_submit) ImageButton ib_submit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.form_activity);
        initBaseView();
        initView();
        initData();
        initPDA();
    }

    private void initView() {
        intent = getIntent();
        act_id = intent.getLongExtra("act_id", 0);
        model_id = intent.getLongExtra("model_id", 0);
        fieldsMap = new HashMap<>();
        headerShowMap = new HashMap<>();
        itemWidget = new HashMap<>();
        mList = new ArrayList<>();
        bodyList = new ArrayList<>();
        tableListData = new ArrayList<>();
        many2oneListMap = new HashMap<>();
        many2oneMoreListMap = new HashMap<>();
        changeMap = new HashMap<>();
        changeSelectList = new HashMap<>();
        many2oneMoreList = new HashMap<>();
        bodyItem = new HashMap<>();
        headerItem = new HashMap<>();
        entryDeleteItems = new ArrayList<>();
        scanHeaderLog = new ArrayList<>();
        scanBodyLog = new ArrayList<>();
        bodyUpdateList = new ArrayList<>();
        layoutInflater = LayoutInflater.from(mContext);
        soundManager = new SoundManager(mContext);

        selectList = new HashMap<>();
        many2oneList = new HashMap<>();
        many2oneHashMap = new HashMap<>();
        many2oneFieldHashMap = new HashMap<>();
        many2oneDefValue = new HashMap<>();
        many2oneOriginMore = new HashMap<>();

        //后退
        ib_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (notSave) {
                    back();
                } else {
                    finish();
                }
            }
        });

        irActWindow = DBHelper.getDaoSession(mContext).getIrActWindowDao().load(act_id);
        title.setText(irActWindow.getName());

        //获取模型访问权限
        QueryBuilder<IrModelAccess> qb3 = DBHelper.getDaoSession(mContext).getIrModelAccessDao().queryBuilder();
        qb3.where(IrModelAccessDao.Properties.Model_id.eq(intent.getLongExtra("model_id", 0)));
        irModelAccess = qb3.list().get(0);
        if (irModelAccess.getPerm_create() || irModelAccess.getPerm_write()) {
            ib_submit.setVisibility(View.VISIBLE);
        }

        //获取One2Many字段
        QueryBuilder<IrModelFields> qb = DBHelper.getDaoSession(mContext).getIrModelFieldsDao().queryBuilder();
        qb.where(IrModelFieldsDao.Properties.Model_id.eq(intent.getLongExtra("model_id", 0)), IrModelFieldsDao.Properties.View_type.eq("form"), IrModelFieldsDao.Properties.Ttype.eq("one2many"), IrModelFieldsDao.Properties.Visiable.eq(1)).limit(1);
        if (qb.list().size() > 0) {
            //获取One2Many的字段
            irModelFieldsOne2Many = qb.list().get(0);
            QueryBuilder<IrModelFields> qb1 = DBHelper.getDaoSession(mContext).getIrModelFieldsDao().queryBuilder();
            qb1.where(IrModelFieldsDao.Properties.Model_id.eq(irModelFieldsOne2Many.getRelation_model_id()), IrModelFieldsDao.Properties.View_type.eq("form")).orderAsc(IrModelFieldsDao.Properties.Sequence);
            irModelFieldsOne2ManyList = qb1.list();
        } else {
            btn_1.setEnabled(false);
            btn_4.setEnabled(false);
        }

        //新建
        if (intent.getStringExtra("action").equals("create")) {
            initHeaderView();
            if (irModelFieldsOne2ManyList != null)
                initBodyView();
            if (irModelAccess.getPerm_check()) {
                btn_2.setEnabled(true);
            }
            getApiDefault();
            showChoiceButton();
        }
    }

    //选单按钮
    @SuppressWarnings("deprecation")
    private void showChoiceButton() {
        if (irActWindow.getChoice_model_id() > 0) {
            Drawable drawable;
            drawable = getResources().getDrawable(R.drawable.ic_keyboard_arrow_down_black_24dp);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            title.setCompoundDrawables(null, null, drawable, null);
            title.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (irModelFieldsOne2Many != null) {
                        ll_main.setVisibility(View.GONE);
                    }
                    Intent intent = new Intent(mContext, ChoiceBill.class);
                    intent.putExtra("act_id", act_id);
                    startActivityForResult(intent, CHOICEBILL);
                }
            });
        }
    }

    /**
     * 初始化表头字段视图
     */
    private void initHeaderView() {
        QueryBuilder<IrModelFields> qb2 = DBHelper.getDaoSession(mContext).getIrModelFieldsDao().queryBuilder();
        qb2.where(IrModelFieldsDao.Properties.Model_id.eq(model_id), IrModelFieldsDao.Properties.View_type.eq("form"), IrModelFieldsDao.Properties.Ttype.notEq("one2many")).orderAsc(IrModelFieldsDao.Properties.Sequence);
        irModelFieldsList = qb2.list();
        int index = 1; //当前布局列
        View view = null;
        //渲染表头字段
        for (int i = 0; i < irModelFieldsList.size(); i++) {
            IrModelFields irModelFields = irModelFieldsList.get(i);
            if (irModelFields.getVisiable()) {
                //显示可见字段
                if (irModelFields.getColspan() == 2) {
                    //占用两列
                    index = 1;
                    view = LayoutInflater.from(mContext).inflate(R.layout.form_activity_item_1col, null);
                    initFiledView(view, irModelFields, 0, 0);
                    ll_wrap.addView(view);
                } else {
                    //占用一列
                    if (index == 1) {
                        //左列
                        index = 2;
                        view = LayoutInflater.from(mContext).inflate(R.layout.form_activity_item_2col, null);
                        initFiledView(view, irModelFields, 1, 0);
                        ll_wrap.addView(view);
                    } else {
                        //右列
                        index = 1;
                        initFiledView(view, irModelFields, 2, 0);
                        LinearLayout ll_view2 = (LinearLayout) view.findViewById(R.id.ll_view2);
                        ll_view2.setVisibility(View.VISIBLE);
                    }
                }
            } else {
                //设置隐藏的字段值
                headerItem.put(irModelFields.getName(), setDefValue(irModelFields.getDef_value(), irModelFields, 0));
            }
        }

        if (irModelFieldsList.size() == 0) {
            btn_2.setEnabled(false);
            btn_3.setEnabled(false);
            ib_submit.setVisibility(View.GONE);
        }
    }

    /**
     * 初始化表体字段视图
     */
    private void initBodyView() {
        //获取表体权限
        QueryBuilder<IrModelAccess> qb = DBHelper.getDaoSession(mContext).getIrModelAccessDao().queryBuilder();
        qb.where(IrModelAccessDao.Properties.Model_id.eq(irModelFieldsOne2Many.getRelation_model_id()));
        if (qb.list().size() > 0) {
            irModelAccessOne2Many = qb.list().get(0);
        }

        //获取主键字段
        QueryBuilder<IrModelFields> qb2 = DBHelper.getDaoSession(mContext).getIrModelFieldsDao().queryBuilder();
        qb2.where(IrModelFieldsDao.Properties.Model_id.eq(irModelFieldsOne2Many.getRelation_model_id()), IrModelFieldsDao.Properties.Primary_key.eq(1));
        if (qb2.list().size() > 0) {
            irModelFieldsOne2ManyKey = qb2.list().get(0);
        }

        //有One2Many字段则配置表格
        final ArrayList<String> tableHeader = new ArrayList<>();
        int index = 1; //当前布局列
        View view = null;
        //渲染One2Many所有字段
        for (int i = 0; i < irModelFieldsOne2ManyList.size(); i++) {
            IrModelFields irModelFields = irModelFieldsOne2ManyList.get(i);
            if (irModelFields.getVisiable()) {
                //显示可见字段
                tableHeader.add(irModelFields.getField_desc());
                if (irModelFields.getColspan() == 2) {
                    //占用两列
                    index = 1;
                    view = LayoutInflater.from(mContext).inflate(R.layout.form_activity_item_1col, null);
                    initFiledView(view, irModelFields, 0, 1);
                    ll_main.addView(view);
                } else {
                    //占用一列
                    if (index == 1) {
                        //左列
                        index = 2;
                        view = LayoutInflater.from(mContext).inflate(R.layout.form_activity_item_2col, null);
                        initFiledView(view, irModelFields, 1, 1);
                        ll_main.addView(view);
                    } else {
                        //右列
                        index = 1;
                        initFiledView(view, irModelFields, 2, 1);
                        LinearLayout ll_view2 = (LinearLayout) view.findViewById(R.id.ll_view2);
                        ll_view2.setVisibility(View.VISIBLE);
                    }
                }
//                    if (i == irModelFieldsOne2ManyList.size() - 1) {
//                        at_text.setImeOptions(EditorInfo.IME_ACTION_DONE);
//                    }
            }
        }
        //初始化表体的表格
        if (tableHeader.size() > 0)
            tableListData.add(0, tableHeader);
        tableDataAdapter = new TableDataAdapter(mContext, tableListData, 28, 14);
        table.setAdapter(tableDataAdapter);
        //点击编辑表格内数据
        if (irModelAccessOne2Many != null && irModelAccessOne2Many.getPerm_write()) {
            table.setOnCellClickListener(new TableFixHeaders.OnCellClickListener() {
                @Override
                public void onItemClick(View view, int row, int column) {
                    ll_main.setVisibility(View.VISIBLE);
                    bodyItem = bodyList.get(row);
                    curRow = row;
                    isClickBody = true;
                    for (int i = 0; i < irModelFieldsOne2ManyList.size(); i++) {
                        IrModelFields irModelFields = irModelFieldsOne2ManyList.get(i);
                        if (irModelFields.getVisiable()) {
                            AutoCompleteTextView actv = (AutoCompleteTextView) itemWidget.get(irModelFields.getId());
                            if (irModelFields.getTtype().equals("float")) {
                                actv.setText(StringUtils.formatNumber(String.valueOf(mList.get(row).get(irModelFields.getName()))));
                            } else {
                                actv.setText(String.valueOf(mList.get(row).get(irModelFields.getName())));
                            }
                            actv.dismissDropDown();
                        }
                    }
//                    table.requestFocus();
//                    table.setFocusable(true);
                    cleanScanLog(1);
                    isClickBody = false;
                }
            });
        }

        //长按删除
        if (irModelAccessOne2Many != null && irModelAccessOne2Many.getPerm_unlink()) {
            table.setOnCellLongClickListener(new TableFixHeaders.OnCellLongClickListener() {
                @Override
                public void onCellLongClick(View view, int row, int column) {
                    final int index = row;
                    new AlertView("提示", "确定删除吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int position) {
                            if (position == 0) {
                                if (bodyList.get(index).get(irModelFieldsOne2ManyKey.getName()) != null) {
                                    entryDeleteItems.add(String.valueOf(bodyList.get(index).get(irModelFieldsOne2ManyKey.getName())));
                                    bodyUpdateList.remove(String.valueOf(bodyList.get(index).get(irModelFieldsOne2ManyKey.getName())));
                                }

                                tableListData.remove(index + 1);
                                mList.remove(index);
                                bodyList.remove(index);
                                tableDataAdapter.notifyDataSetChanged();
                                cleanBodyForm();
                            }
                        }
                    }).show();
                }
            });
        }

    }

    /**
     * 默认值设置
     *
     * @param value         默认值
     * @param irModelFields 字段
     * @param p             0表头，1表体
     * @return 默认值
     */
    private String setDefValue(String value, IrModelFields irModelFields, int p) {
        if (p == 0 && intent.getStringExtra("action").equals("read")) {
            //表头在读取单据时默认值的设置
            String val = "";
            if (irModelFields.getVisiable()) {
                if (headerShowMap.get(irModelFields.getName()) != null)
                    val = headerShowMap.get(irModelFields.getName()).toString();
                if (irModelFields.getTtype().equals("float")) {
                    val = StringUtils.formatNumber(val);
                }
            } else {
                val = headerItem.get(irModelFields.getName()).toString();
            }
            if (irModelFields.getTtype().equals("date")) {
                val = val.equals("") ? "" : val.substring(0, 10);
            }
            return val;
        } else {
            if (irModelFields.getTtype().equals("many2one")) {
                if (p == 0) {
                    headerItem.put(irModelFields.getName(), many2oneDefValue.get(irModelFields.getId()));
                } else {
                    bodyItem.put(irModelFields.getName(), many2oneDefValue.get(irModelFields.getId()));
                }
            }

            if (value.indexOf("client.getDatetime") != -1) {
                return TimeUtils.getNowTimeString("yyyy-MM-dd HH:mm:ss");
            } else if (value.indexOf("client.getDate") != -1) {
                return TimeUtils.getNowTimeString("yyyy-MM-dd");
            } else if (value.indexOf("client.getUsername") != -1) {
                return SPData.getUserinfo().getString("username", "");
            } else if (value.indexOf("fun.") != -1) {
                return "";
            } else if (value.indexOf("api_") != -1 && value.indexOf("_api") != -1) {
                return "";
            } else {
                return value;
            }
        }
    }

    //初始化表单数据
    private void initData() {
        if (intent.getStringExtra("action").equals("read")) {
            HashMap<String, Object> param = new HashMap<>();
            param.put("key_value", intent.getStringExtra(intent.getStringExtra("key_name")));
            param.put("key_name", intent.getStringExtra("key_name"));
            param.put("model_id", intent.getLongExtra("model_id", 0));
            HttpRequest httpRequest = new HttpRequest(mContext, WebApi.api(), "getFormData", JSON.toJSONString(param), true, true);
            httpRequest.setmWhat(-1);
            httpRequest.send(new SimpleHttpListener<JSONObject>() {
                @Override
                public void onSucceed(int what, Response<JSONObject> response) {
                    super.onSucceed(what, response);
                    if (what == -1) {
                        JSONObject header_show = response.get().optJSONObject("data").optJSONObject("header_show");
                        Iterator itShow = header_show.keys();
                        while (itShow.hasNext()) {
                            String key = (String) itShow.next();
                            Object value = header_show.opt(key);
                            headerShowMap.put(key, value);
                        }

                        JSONObject header = response.get().optJSONObject("data").optJSONObject("header");
                        Iterator it = header.keys();
                        while (it.hasNext()) {
                            String key = (String) it.next();
                            Object value = header.opt(key);
                            headerItem.put(key, value);
                        }

                        //判断是否已经审核
                        if (response.get().optJSONObject("data").optInt("isCheck") == 0) {
                            if (irModelAccess.getPerm_check()) {
                                btn_2.setEnabled(true);
                            }
                            showChoiceButton();
                        } else {
                            isCheck = true;
                            ib_submit.setVisibility(View.GONE);
                            if (irModelAccess.getPerm_uncheck()) {
                                btn_3.setEnabled(true);
                            }
                            btn_4.setEnabled(false);
                        }

                        if (irModelFieldsOne2ManyList != null) {
                            JSONArray body_show = response.get().optJSONObject("data").optJSONArray("body_show");
                            JSONArray body = response.get().optJSONObject("data").optJSONArray("body");
                            for (int i = 0; i < body_show.length(); i++) {
                                JSONObject item = body_show.optJSONObject(i);
                                ArrayList<String> tabledata = new ArrayList<>();
                                HashMap<String, Object> map = new HashMap<>();
                                for (int j = 0; j < irModelFieldsOne2ManyList.size(); j++) {
                                    IrModelFields irModelFields = irModelFieldsOne2ManyList.get(j);
                                    if (irModelFields.getVisiable()) {
                                        if (irModelFields.getTtype().equals("float")) {
                                            tabledata.add(StringUtils.formatNumber(String.valueOf(item.opt(irModelFields.getName()))));
                                            map.put(irModelFields.getName(), item.opt(irModelFields.getName()));
                                        } else {
                                            tabledata.add(String.valueOf(item.opt(irModelFields.getName())));
                                            map.put(irModelFields.getName(), item.opt(irModelFields.getName()));
                                        }

                                    }
                                }
                                mList.add(map);
                                tableListData.add(tabledata);
                            }

                            //表体默认值
                            if (!isCheck) {
                                JSONObject body_default = response.get().optJSONObject("data").optJSONObject("body_default");
                                for (int i = 0; i < irModelFieldsOne2ManyList.size(); i++) {
                                    IrModelFields irModelFields = irModelFieldsOne2ManyList.get(i);
                                    if (irModelFields.getDef_value().indexOf("api_") > -1 && irModelFields.getDef_value().indexOf("_api") > -1) {
                                        irModelFields.setDef_value(body_default.optString(String.valueOf(irModelFields.getId())));
                                        if (irModelFields.getVisiable()) {
                                            AutoCompleteTextView actv = (AutoCompleteTextView) itemWidget.get(irModelFields.getId());
                                            actv.setText(body_default.optString(String.valueOf(irModelFields.getId())));
                                        } else {
                                            bodyItem.put(irModelFields.getName(), body_default.optString(String.valueOf(irModelFields.getId())));
                                        }
                                    } else if (irModelFields.getTtype().equals("many2one") && !irModelFields.getDef_value().equals("")) {
                                        many2oneDefValue.put(irModelFields.getId(), body_default.optString(String.valueOf(irModelFields.getId())));
                                        bodyItem.put(irModelFields.getName(), body_default.optString(String.valueOf(irModelFields.getId())));
                                    }
                                }
                            }

                            //保存到临时值中
                            for (int i = 0; i < body.length(); i++) {
                                JSONObject item = body.optJSONObject(i);
                                HashMap<String, Object> map = new HashMap<>();
                                Iterator itBody = item.keys();
                                while (itBody.hasNext()) {
                                    String key = (String) itBody.next();
                                    Object value = item.opt(key);
                                    map.put(key, value);
                                }
                                bodyList.add(map);
                            }
                            initBodyView();
                        }
                        initHeaderView();
                    }
                }
            });
        }
    }

    //初始化PDA
    private void initPDA() {
        //判断是否为PDA
        String deviceModel = Build.MODEL;
        if (deviceModel.length() > 5) {
            if (deviceModel.substring(0, 5).equals("HT380")) {
                isPDA = true;
                scanManager = BarcodeManager.getInstance();
                scanManager.Barcode_Open(mContext, new BarcodeManager.Callback() {
                    @Override
                    public void Barcode_Read(byte[] bytes, String s, int i) {
                        soundManager.playSound();
                        getScanResult(new String(bytes));
                    }
                });
            }
        }
    }

    //处理扫描后的结果
    private void getScanResult(String code) {
        if (!TextUtils.isEmpty(code)) {
            isScaning = true;
            IrModelFields field = fieldsMap.get(curFieldId);
            AutoCompleteTextView actv = (AutoCompleteTextView) itemWidget.get(field.getId());
            actv.setText(code);

            //记录扫描位置
            if (sv_wrap.getVisibility() == View.GONE) {
                if (scanBodyLog.size() > 0) {
                    int i;
                    for (i = 0; i < scanBodyLog.size(); i++) {
                        if ((long) scanBodyLog.get(i).get("field_id") == curFieldId) {
                            scanBodyLog.get(i).put("scan", true);
                            break;
                        }
                    }
                    if (i == scanBodyLog.size() - 1) {
                        cleanScanLog(1);
                    }
                }
            } else {
                if (scanHeaderLog.size() > 0) {
                    int i;
                    for (i = 0; i < scanHeaderLog.size(); i++) {
                        if ((long) scanHeaderLog.get(i).get("field_id") == curFieldId) {
                            scanHeaderLog.get(i).put("scan", true);
                            break;
                        }
                    }
                    if (i == scanHeaderLog.size() - 1) {
                        cleanScanLog(0);
                    }
                }
            }
        } else {
            isScaning = false;
        }

    }

    /**
     * 清除扫描记录
     *
     * @param p 0表头，1表体
     */
    private void cleanScanLog(int p) {
        if (p == 0) {
            for (int i = 0; i < scanHeaderLog.size(); i++) {
                scanHeaderLog.get(i).put("scan", false);
            }
        } else {
            for (int i = 0; i < scanBodyLog.size(); i++) {
                scanBodyLog.get(i).put("scan", false);
            }
        }
    }

    /**
     * 初始化字段视图
     *
     * @param view          视图
     * @param irModelFields 字段
     * @param type          0占两列，1、2各占1列
     * @param p             0表头，1表体
     */
    private void initFiledView(View view, IrModelFields irModelFields, int type, int p) {
        switch (irModelFields.getTtype()) {
            case "string":
                initString(view, irModelFields, type, p);
                break;
            case "int":
                initInt(view, irModelFields, type, p);
                break;
            case "float":
                initFloat(view, irModelFields, type, p);
                break;
            case "many2one":
                many2oneFieldHashMap.put(irModelFields.getId(), new InitMany2One(view, irModelFields, type, p));
                break;
            case "date":
                initDate(view, irModelFields, type, p);
                break;
            case "datetime":
                initDatetime(view, irModelFields, type, p);
                break;
            case "text":
                initText(view, irModelFields, type, p);
                break;
        }
        initScan(view, irModelFields, type, p);
    }

    //初始化字符串字段string
    private void initString(View view, final IrModelFields irModelFields, int type, final int p) {
        TextView tv_title = null;
        AutoCompleteTextView at_text = null;
        if (type == 0) {
            tv_title = (TextView) view.findViewById(R.id.tv_title);
            at_text = (AutoCompleteTextView) view.findViewById(R.id.at_text);
        } else if (type == 1) {
            tv_title = (TextView) view.findViewById(R.id.tv_title1);
            at_text = (AutoCompleteTextView) view.findViewById(R.id.at_text1);
        } else if (type == 2) {
            tv_title = (TextView) view.findViewById(R.id.tv_title2);
            at_text = (AutoCompleteTextView) view.findViewById(R.id.at_text2);
        }
        tv_title.setText(irModelFields.getField_desc());
        at_text.setVisibility(View.VISIBLE);
        itemWidget.put(irModelFields.getId(), at_text);
        fieldsMap.put(irModelFields.getId(), irModelFields); //加入到全局字段hashmap中
        if (irModelFields.getReadonly()) {
            at_text.setFocusableInTouchMode(false);
            at_text.setBackgroundResource(R.drawable.bg_transparent);
            at_text.setFocusable(false);
        }
        //保存临时值
        at_text.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                notSave = true;
                if (p == 0)
                    headerItem.put(irModelFields.getName(), s.toString());
                else
                    bodyItem.put(irModelFields.getName(), s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        at_text.setText(setDefValue(irModelFields.getDef_value(), irModelFields, p));
    }

    //初始化int
    private void initInt(View view, final IrModelFields irModelFields, int type, final int p) {
        TextView tv_title = null;
        AutoCompleteTextView at_text = null;
        if (type == 0) {
            tv_title = (TextView) view.findViewById(R.id.tv_title);
            at_text = (AutoCompleteTextView) view.findViewById(R.id.at_text);
        } else if (type == 1) {
            tv_title = (TextView) view.findViewById(R.id.tv_title1);
            at_text = (AutoCompleteTextView) view.findViewById(R.id.at_text1);
        } else if (type == 2) {
            tv_title = (TextView) view.findViewById(R.id.tv_title2);
            at_text = (AutoCompleteTextView) view.findViewById(R.id.at_text2);
        }
        tv_title.setText(irModelFields.getField_desc());

        at_text.setVisibility(View.VISIBLE);
        at_text.setInputType(InputType.TYPE_CLASS_NUMBER);
        itemWidget.put(irModelFields.getId(), at_text);
        fieldsMap.put(irModelFields.getId(), irModelFields); //加入到全局字段hashmap中
        if (irModelFields.getReadonly()) {
            at_text.setFocusableInTouchMode(false);
            at_text.setBackgroundResource(R.drawable.bg_transparent);
            at_text.setFocusable(false);
        }
        //保存临时值
        at_text.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                notSave = true;
                if (p == 0)
                    headerItem.put(irModelFields.getName(), s.toString().equals("") ? "0" : s.toString());
                else
                    bodyItem.put(irModelFields.getName(), s.toString().equals("") ? "0" : s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        at_text.setText(setDefValue(irModelFields.getDef_value(), irModelFields, p));
    }

    //初始化float
    private void initFloat(View view, final IrModelFields irModelFields, int type, final int p) {
        TextView tv_title = null;
        AutoCompleteTextView at_text = null;
        if (type == 0) {
            tv_title = (TextView) view.findViewById(R.id.tv_title);
            at_text = (AutoCompleteTextView) view.findViewById(R.id.at_text);
        } else if (type == 1) {
            tv_title = (TextView) view.findViewById(R.id.tv_title1);
            at_text = (AutoCompleteTextView) view.findViewById(R.id.at_text1);
        } else if (type == 2) {
            tv_title = (TextView) view.findViewById(R.id.tv_title2);
            at_text = (AutoCompleteTextView) view.findViewById(R.id.at_text2);
        }
        tv_title.setText(irModelFields.getField_desc());

        at_text.setVisibility(View.VISIBLE);
        at_text.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        itemWidget.put(irModelFields.getId(), at_text);
        fieldsMap.put(irModelFields.getId(), irModelFields); //加入到全局字段hashmap中
        if (irModelFields.getReadonly()) {
            at_text.setFocusableInTouchMode(false);
            at_text.setBackgroundResource(R.drawable.bg_transparent);
            at_text.setFocusable(false);
        }
        at_text.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                notSave = true;
                if (p == 0)
                    headerItem.put(irModelFields.getName(), s.toString().equals("") ? "0" : s.toString());
                else
                    bodyItem.put(irModelFields.getName(), s.toString().equals("") ? "0" : s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        at_text.setText(setDefValue(irModelFields.getDef_value(), irModelFields, p));
    }

    //初始化many2one字段
    public class InitMany2One {
        private View view;
        private IrModelFields irModelFields;
        private int type;
        private int p;
        private List<IrModelFields> changeFields;
        private AutoCompleteTextView at_text;
        private List<IrModelFields> relation_fields;

        public InitMany2One(View view, IrModelFields irModelFields, int type, int p) {
            this.view = view;
            this.irModelFields = irModelFields;
            this.type = type;
            this.p = p;
            init();
        }

        private void init() {
            TextView tv_title = null;
            if (type == 0) {
                tv_title = (TextView) view.findViewById(R.id.tv_title);
                at_text = (AutoCompleteTextView) view.findViewById(R.id.at_text);
            } else if (type == 1) {
                tv_title = (TextView) view.findViewById(R.id.tv_title1);
                at_text = (AutoCompleteTextView) view.findViewById(R.id.at_text1);
            } else if (type == 2) {
                tv_title = (TextView) view.findViewById(R.id.tv_title2);
                at_text = (AutoCompleteTextView) view.findViewById(R.id.at_text2);
            }
            many2oneOriginMore.put(irModelFields.getId(), false);
            at_text.setText(setDefValue(irModelFields.getDef_value(), irModelFields, p));
            at_text.setVisibility(View.VISIBLE);
            itemWidget.put(irModelFields.getId(), at_text);
            fieldsMap.put(irModelFields.getId(), irModelFields); //加入到全局字段hashmap中

            if (irModelFields.getReadonly()) {
                tv_title.setText(irModelFields.getField_desc());
                at_text.setFocusableInTouchMode(false);
                at_text.setBackgroundResource(R.drawable.bg_transparent);
                at_text.setFocusable(false);
            } else {
                tv_title.setText(irModelFields.getField_desc() + " ▼");
                tv_title.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        KeyboardUtils.hideSoftInput(mActivity);
                        getMany2OneMore();
                    }
                });
            }

            //查询关联模型内的字段
            QueryBuilder<IrModelFields> qb = DBHelper.getDaoSession(mContext).getIrModelFieldsDao().queryBuilder();
            qb.where(IrModelFieldsDao.Properties.Model_id.eq(irModelFields.getRelation_model_id()));
            relation_fields = qb.list();

            //获取关联改变的字段
            QueryBuilder<IrModelFields> qb2 = DBHelper.getDaoSession(mContext).getIrModelFieldsDao().queryBuilder();
            qb2.where(IrModelFieldsDao.Properties.Model_id.eq(irModelFields.getModel_id()), IrModelFieldsDao.Properties.View_type.eq("form"), IrModelFieldsDao.Properties.Rel_change_field.eq(irModelFields.getName()));
            changeFields = qb2.list();

            //保存临时值
            at_text.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    if (!isTextChanged && !isClickBody && !many2oneOriginMore.get(irModelFields.getId())) {
                        isTextChanged = true;
                        //获取提示数据
                        if ((count > 0 || before > 0) && !originList && !many2oneOriginMore.get(irModelFields.getId())) {
                            if (many2oneHashMap.get(irModelFields.getId()) == null) {
                                many2oneHashMap.put(irModelFields.getId(), new Many2One(irModelFields, at_text, p));
                            }
                            many2oneHashMap.get(irModelFields.getId()).getData();
                        }
                        originList = false;
                    }

                    //把填写的内容临时保存在一个map中，点击"保存"按钮时保存到另外一个map中
                    if (s.toString().equals("")) {
                        if (p == 0)
                            headerItem.put(irModelFields.getName(), "");
                        else
                            bodyItem.put(irModelFields.getName(), "");
                    } else {
                        if (changeSelectList.get(irModelFields.getId()) != null && many2oneOriginMore.get(irModelFields.getId())) {
                            if (p == 0) {
                                headerItem.put(irModelFields.getName(), many2oneMoreList.get(irModelFields.getId()).get(changeSelectList.get(irModelFields.getId())).get(irModelFields.getRelation_field()));
                            } else {
                                bodyItem.put(irModelFields.getName(), many2oneMoreList.get(irModelFields.getId()).get(changeSelectList.get(irModelFields.getId())).get(irModelFields.getRelation_field()));
                            }
                        }
                    }

                    //处理关联改变字段，点击表体的某条记录时不处理
                    if (changeFields.size() > 0 && !isClickBody) {
                        for (int i = 0; i < changeFields.size(); i++) {
                            IrModelFields f = changeFields.get(i);
                            many2oneOriginMore.put(f.getId(), true);
                            //判断字段有没有对应
                            if (changeSelectList.get(irModelFields.getId()) != null && many2oneOriginMore.get(irModelFields.getId())) {
                                //保存值
                                if (!TextUtils.isEmpty(f.getChange_save_field())) {
                                    if (p == 0)
                                        headerItem.put(f.getName(), many2oneMoreList.get(irModelFields.getId()).get(changeSelectList.get(irModelFields.getId())).get(f.getChange_save_field()));
                                    else
                                        bodyItem.put(f.getName(), many2oneMoreList.get(irModelFields.getId()).get(changeSelectList.get(irModelFields.getId())).get(f.getChange_save_field()));
                                } else {
                                    if (p == 0)
                                        headerItem.put(f.getName(), headerItem.get(irModelFields.getName()));
                                    else
                                        bodyItem.put(f.getName(), bodyItem.get(irModelFields.getName()));
                                }

                                //判断是否要显示
                                if (f.getVisiable()) {
                                    AutoCompleteTextView actv = (AutoCompleteTextView) itemWidget.get(f.getId());
                                    //显示值
                                    if (!TextUtils.isEmpty(f.getChange_display_field())) {
                                        actv.setText(String.valueOf(many2oneMoreList.get(irModelFields.getId()).get(changeSelectList.get(irModelFields.getId())).get(f.getChange_display_field())));
                                    } else {
                                        actv.setText(String.valueOf(many2oneMoreList.get(irModelFields.getId()).get(changeSelectList.get(irModelFields.getId())).get(f.getChange_save_field())));
                                    }
                                }
                            }
                        }
                    }
                    many2oneOriginMore.put(irModelFields.getId(), false);
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });
        }

        //获取many2one类型字段的更多数据，可带入其他字段的值
        private void getMany2OneMore() {
            HashMap<String, Object> param = new HashMap<>();
            //获取更多的时候处理依赖字段
            HashMap<String, Object> depend = new HashMap<>();
            if (!TextUtils.isEmpty(irModelFields.getDepend_field()) && !TextUtils.isEmpty(irModelFields.getSelect_cmd())) {
                String[] depends = irModelFields.getDepend_field().split(",");
                for (int i = 0; i < depends.length; i++) {
                    QueryBuilder<IrModelFields> qb = DBHelper.getDaoSession(mContext).getIrModelFieldsDao().queryBuilder();
                    qb.where(IrModelFieldsDao.Properties.Model_id.eq(irModelFields.getModel_id()), IrModelFieldsDao.Properties.Name.eq(depends[i]));
                    IrModelFields dependField = qb.limit(1).list().get(0);

                    //依赖的是自己，则把界面上填的值传入
                    if (dependField.getId() == irModelFields.getId()) {
                        AutoCompleteTextView actv = (AutoCompleteTextView) itemWidget.get(dependField.getId());
                        if (!TextUtils.isEmpty(actv.getText().toString())) {
                            depend.put(depends[i], actv.getText().toString());
                        }
                    } else {
                        if (p == 0) {
                            //表头
                            if (headerItem.get(dependField.getName()) != null)
                                depend.put(depends[i], headerItem.get(dependField.getName()));
                        } else if (p == 1) {
                            //表体
                            if (bodyItem.get(dependField.getName()) != null)
                                depend.put(depends[i], bodyItem.get(dependField.getName()));
                        }
                    }
                }
                if (depend.size() > 0) {
                    param.put("depend", JSON.toJSONString(depend));
                }
            }

            //请求获取更多数据
            param.put("field_id", irModelFields.getId());
            HttpRequest httpRequest = new HttpRequest(mContext, WebApi.api(), "getMany2oneMore", JSON.toJSONString(param), true, true);
            httpRequest.send(new SimpleHttpListener<JSONObject>() {
                @Override
                public void onSucceed(int what, Response<JSONObject> response) {
                    super.onSucceed(what, response);
                    JSONObject data = response.get().optJSONObject("data");
                    com.alibaba.fastjson.JSONArray list = JSON.parseArray(data.optString("list"));
                    //获取更多
                    ArrayList<HashMap<String, Object>> rowList = new ArrayList<>();
                    ArrayList<String> showList = new ArrayList<>();
                    ArrayList<HashMap<String, Object>> changeItemList = new ArrayList<>();
                    for (int i = 0; i < list.size(); i++) {
                        HashMap<String, Object> row = new HashMap<>();
                        com.alibaba.fastjson.JSONObject item = list.getJSONObject(i);
                        for (int j = 0; j < relation_fields.size(); j++) {
                            row.put(relation_fields.get(j).getName(), item.get(relation_fields.get(j).getName()));
                        }
                        changeItemList.add(row);
                        rowList.add(row);
                        showList.add(String.valueOf(row.get(irModelFields.getRel_display_field())));
                    }
                    many2oneMoreListMap.put(irModelFields.getId(), showList);
                    many2oneMoreList.put(irModelFields.getId(), changeItemList);
                    Many2OneAdapter many2OneAdapter = new Many2OneAdapter(mContext, rowList, relation_fields);
                    View view = layoutInflater.inflate(R.layout.many2one_list, null);
                    ListView lv = (ListView) view.findViewById(R.id.lv);
                    lv.setAdapter(many2OneAdapter);
                    dialog = new AlertDialog.Builder(mContext).setTitle("选择" + irModelFields.getField_desc()).setView(view).create();
                    dialog.show();
                    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            dialog.dismiss();
                            many2oneOriginMore.put(irModelFields.getId(), true);
                            changeSelectList.put(irModelFields.getId(), position);
                            at_text.setText(many2oneMoreListMap.get(irModelFields.getId()).get(position));
                            at_text.dismissDropDown();
                        }
                    });
                }
            });
        }

        public List<IrModelFields> getChangeFields() {
            return changeFields;
        }

        public List<IrModelFields> getRelation_fields() {
            return relation_fields;
        }
    }

    //初始化短日期字段date
    private void initDate(View view, final IrModelFields irModelFields, int type, final int p) {
        TextView tv_title = null;
        AutoCompleteTextView at_text = null;
        if (type == 0) {
            tv_title = (TextView) view.findViewById(R.id.tv_title);
            at_text = (AutoCompleteTextView) view.findViewById(R.id.at_text);
        } else if (type == 1) {
            tv_title = (TextView) view.findViewById(R.id.tv_title1);
            at_text = (AutoCompleteTextView) view.findViewById(R.id.at_text1);
        } else if (type == 2) {
            tv_title = (TextView) view.findViewById(R.id.tv_title2);
            at_text = (AutoCompleteTextView) view.findViewById(R.id.at_text2);
        }
        tv_title.setText(irModelFields.getField_desc());
        at_text.setVisibility(View.VISIBLE);
        itemWidget.put(irModelFields.getId(), at_text);
        fieldsMap.put(irModelFields.getId(), irModelFields); //加入到全局字段hashmap中
        if (irModelFields.getReadonly()) {
            at_text.setFocusableInTouchMode(false);
            at_text.setBackgroundResource(R.drawable.bg_transparent);
            at_text.setFocusable(false);
        } else {
            at_text.setFocusableInTouchMode(false);
            at_text.setFocusable(false);
            at_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    KeyboardUtils.hideSoftInput(mActivity);
                    DatePickerDialogUtil datePickerDialogUtil = new DatePickerDialogUtil(mActivity, ((AutoCompleteTextView) itemWidget.get(irModelFields.getId())).getText().toString(), true);
                    datePickerDialogUtil.datePickerAlertDialog(((AutoCompleteTextView) itemWidget.get(irModelFields.getId())));
                }
            });
        }

        //保存临时值
        at_text.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                notSave = true;
                if (p == 0)
                    headerItem.put(irModelFields.getName(), s.toString());
                else
                    bodyItem.put(irModelFields.getName(), s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        at_text.setText(setDefValue(irModelFields.getDef_value(), irModelFields, p));
    }


    //初始化长日期字段datetime
    private void initDatetime(View view, final IrModelFields irModelFields, int type, final int p) {
        TextView tv_title = null;
        AutoCompleteTextView at_text = null;
        if (type == 0) {
            tv_title = (TextView) view.findViewById(R.id.tv_title);
            at_text = (AutoCompleteTextView) view.findViewById(R.id.at_text);
        } else if (type == 1) {
            tv_title = (TextView) view.findViewById(R.id.tv_title1);
            at_text = (AutoCompleteTextView) view.findViewById(R.id.at_text1);
        } else if (type == 2) {
            tv_title = (TextView) view.findViewById(R.id.tv_title2);
            at_text = (AutoCompleteTextView) view.findViewById(R.id.at_text2);
        }
        tv_title.setText(irModelFields.getField_desc());
        at_text.setVisibility(View.VISIBLE);
        itemWidget.put(irModelFields.getId(), at_text);
        fieldsMap.put(irModelFields.getId(), irModelFields); //加入到全局字段hashmap中
        if (irModelFields.getReadonly()) {
            at_text.setFocusableInTouchMode(false);
            at_text.setBackgroundResource(R.drawable.bg_transparent);
            at_text.setFocusable(false);
        } else {
            at_text.setFocusableInTouchMode(false);
            at_text.setFocusable(false);
            at_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    KeyboardUtils.hideSoftInput(mActivity);
                    DateTimePickerDialogUtil dateTimePickerDialogUtil = new DateTimePickerDialogUtil(mActivity, ((AutoCompleteTextView) itemWidget.get(irModelFields.getId())).getText().toString());
                    dateTimePickerDialogUtil.dateTimePickerDialog(((AutoCompleteTextView) itemWidget.get(irModelFields.getId())));
                }
            });
        }

        //保存临时值
        at_text.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                notSave = true;
                if (p == 0)
                    headerItem.put(irModelFields.getName(), s.toString());
                else
                    bodyItem.put(irModelFields.getName(), s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        at_text.setText(setDefValue(irModelFields.getDef_value(), irModelFields, p));
    }

    //初始化字符串字段string
    private void initText(View view, final IrModelFields irModelFields, int type, final int p) {
        TextView tv_title = null;
        AutoCompleteTextView at_text = null;
        if (type == 0) {
            tv_title = (TextView) view.findViewById(R.id.tv_title);
            at_text = (AutoCompleteTextView) view.findViewById(R.id.at_textarea);
        } else if (type == 1) {
            tv_title = (TextView) view.findViewById(R.id.tv_title1);
            at_text = (AutoCompleteTextView) view.findViewById(R.id.at_textarea1);
        } else if (type == 2) {
            tv_title = (TextView) view.findViewById(R.id.tv_title2);
            at_text = (AutoCompleteTextView) view.findViewById(R.id.at_textarea2);
        }

        tv_title.setText(irModelFields.getField_desc());
        at_text.setVisibility(View.VISIBLE);
        itemWidget.put(irModelFields.getId(), at_text);
        fieldsMap.put(irModelFields.getId(), irModelFields); //加入到全局字段hashmap中
        if (irModelFields.getReadonly()) {
            at_text.setFocusableInTouchMode(false);
            at_text.setBackgroundResource(R.drawable.bg_transparent);
            at_text.setFocusable(false);
        }
        //保存临时值
        at_text.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                notSave = true;
                if (p == 0)
                    headerItem.put(irModelFields.getName(), s.toString());
                else
                    bodyItem.put(irModelFields.getName(), s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        at_text.setText(setDefValue(irModelFields.getDef_value(), irModelFields, p));
    }

    //初始化扫描
    private void initScan(View view, IrModelFields irModelFields, int colType, int p) {
        if (irModelFields.getScan() && colType == 0) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("scan", false);
            map.put("field_id", irModelFields.getId());
            if (p == 0) {
                scanHeaderLog.add(map);
            } else {
                scanBodyLog.add(map);
            }
            Button btn_scan = (Button) view.findViewById(R.id.btn_scan);
            btn_scan.setVisibility(View.VISIBLE);
            btn_scan.setTag(irModelFields.getId());
            btn_scan.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    curFieldId = (long) v.getTag();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        checkCameraPermission();
                    } else {
                        openScan();
                    }
                }
            });
        }
    }

    //打开扫描界面扫描条形码或二维码
    private void openScan() {
        if (!ButtonUtils.isFastDoubleClick((int) curFieldId)) {
            if (isPDA) {
                scanManager.Barcode_Start();
            } else {
                Intent openCameraIntent = new Intent(mContext, CaptureActivity.class);
                openCameraIntent.putExtra("from", FormActivity.class.getName().toString());
                startActivityForResult(openCameraIntent, REQUESTCODE_CAMERA);
            }
        }
    }

    //初始化获取many2one匹配到的数据
    public class Many2One {
        private IrModelFields irModelFields;
        private AutoCompleteTextView actv;
        private String[] strings;
        private ArrayAdapter<String> arrayAdapter; //提示适配器
        private int p;

        public Many2One(final IrModelFields irModelFields, AutoCompleteTextView actv, int initP) {
            this.irModelFields = irModelFields;
            this.actv = actv;
            this.p = initP;
            //点击之后
            actv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    //保存选中的位置
                    selectList.put(irModelFields.getId(), position);
                    originList = true;
                    show(position);
                }
            });
        }

        //保存获取到的值和通过改变获取到的值
        private void show(int position) {
            if (p == 0)
                headerItem.put(irModelFields.getName(), many2oneList.get(irModelFields.getId()).get(position).get(irModelFields.getRelation_field()));
            else
                bodyItem.put(irModelFields.getName(), many2oneList.get(irModelFields.getId()).get(position).get(irModelFields.getRelation_field()));

            //处理关联改变字段
            List<IrModelFields> changeFields = many2oneFieldHashMap.get(irModelFields.getId()).getChangeFields();
            if (changeFields.size() > 0) {
                for (int i = 0; i < changeFields.size(); i++) {
                    IrModelFields f = changeFields.get(i);
                    //保存值
                    if (!TextUtils.isEmpty(f.getChange_save_field())) {
                        if (many2oneList.get(irModelFields.getId()).get(position).get(f.getChange_save_field()) != null) {
                            if (p == 0)
                                headerItem.put(f.getName(), many2oneList.get(irModelFields.getId()).get(position).get(f.getChange_save_field()));
                            else
                                bodyItem.put(f.getName(), many2oneList.get(irModelFields.getId()).get(position).get(f.getChange_save_field()));
                        } else {
                            ToastUtils.showLongToast("关联模型中字段 " + f.getChange_save_field() + " 的值不存在");
                            if (p == 0)
                                headerItem.put(f.getName(), "");
                            else
                                bodyItem.put(f.getName(), "");
                        }
                    } else {
                        if (p == 0)
                            headerItem.put(f.getName(), headerItem.get(irModelFields.getName()));
                        else
                            bodyItem.put(f.getName(), bodyItem.get(irModelFields.getName()));
                    }

                    //判断是否要显示
                    if (f.getVisiable()) {
                        AutoCompleteTextView actv = (AutoCompleteTextView) itemWidget.get(f.getId());
                        //显示值
                        if (!TextUtils.isEmpty(f.getChange_display_field())) {
                            if (many2oneList.get(irModelFields.getId()).get(position).get(f.getChange_display_field()) != null) {
                                actv.setText(String.valueOf(many2oneList.get(irModelFields.getId()).get(position).get(f.getChange_display_field())));
                            } else {
                                ToastUtils.showLongToast("关联模型中字段 " + f.getChange_save_field() + " 的值不存在");
                                actv.setText("");
                            }
                        } else {
                            if (many2oneList.get(irModelFields.getId()).get(position).get(f.getChange_save_field()) != null) {
                                actv.setText(String.valueOf(many2oneList.get(irModelFields.getId()).get(position).get(f.getChange_save_field())));
                            }
                        }
                    }
                }
            }
        }

        //从服务器获取匹配到的数据
        private void getData() {
            HashMap<String, Object> param = new HashMap<>();
            param.put("searchValue", actv.getText().toString());
            param.put("field_id", irModelFields.getId());
            if (!isRequest) {
                isRequest = true;
                HttpRequest httpRequest = new HttpRequest(mContext, WebApi.api(), "getMany2oneList", JSON.toJSONString(param), true, false);
                httpRequest.send(new SimpleHttpListener<JSONObject>() {
                    @Override
                    public void onSucceed(int what, Response<JSONObject> response) {
                        super.onSucceed(what, response);
                        if (!originList) {
                            com.alibaba.fastjson.JSONObject json = JSON.parseObject(response.get().toString());
                            com.alibaba.fastjson.JSONArray list = json.getJSONObject("data").getJSONArray("list");
                            if (list.size() > 0) {
                                int index = -1;
                                strings = new String[list.size()];
                                ArrayList<HashMap<String, Object>> changeItemList = new ArrayList<>();

                                List<IrModelFields> relation_fields = many2oneFieldHashMap.get(irModelFields.getId()).getRelation_fields();
                                for (int i = 0; i < list.size(); i++) {
                                    HashMap<String, Object> row = new HashMap<>();
                                    com.alibaba.fastjson.JSONObject item = list.getJSONObject(i);
                                    strings[i] = item.getString(irModelFields.getRel_display_field());
                                    for (int j = 0; j < relation_fields.size(); j++) {
                                        row.put(relation_fields.get(j).getName(), item.get(relation_fields.get(j).getName()));
                                    }
                                    changeItemList.add(row);
                                    //拿到第一条匹配的数据
                                    if (strings[i].equals(actv.getText().toString()) && index < 0) {
                                        index = i;
                                    }
                                }
                                many2oneList.put(irModelFields.getId(), changeItemList);

                                arrayAdapter = new ArrayAdapter<>(mContext, android.R.layout.simple_list_item_1, strings);
                                actv.setAdapter(arrayAdapter);
                                actv.setThreshold(1);
                                if (isScaning) {
                                    actv.dismissDropDown();
                                } else {
                                    actv.showDropDown();
                                }

                                if (index > -1) {
                                    show(index);
                                } else {
                                    if (p == 0)
                                        headerItem.remove(irModelFields.getName());
                                    else
                                        bodyItem.remove(irModelFields.getName());
                                }
                            } else {
                                actv.dismissDropDown();
                            }
                        } else {
                            actv.dismissDropDown();
                        }
                        originList = false;
                        isRequest = false;
                        isTextChanged = false;
                        isScaning = false;
                    }

                    @Override
                    public void onFailed(int what, Response<JSONObject> response) {
                        super.onFailed(what, response);
                        if (originList) {
                            //有点过提示
                            originList = false;
                            actv.dismissDropDown();
                        }
                        isRequest = false;
                        isTextChanged = false;
                        isScaning = false;
                    }
                });
            }
        }
    }

    //表头、表体切换
    @OnClick(R.id.btn_1)
    public void f1() {
        if (btn_1.isEnabled()) {
            KeyboardUtils.hideSoftInput(this);
            if (sv_wrap.getVisibility() == View.GONE) {
                sv_wrap.setVisibility(View.VISIBLE);
                ll_main.setVisibility(View.GONE);
                table.setVisibility(View.GONE);
                btn_1.setText("F1表体");
            } else {
                sv_wrap.setVisibility(View.GONE);
                ll_main.setVisibility(View.VISIBLE);
                table.setVisibility(View.VISIBLE);
                btn_1.setText("F1表头");
            }
        }
    }

    //审核
    @OnClick(R.id.btn_2)
    public void f2() {
        if (btn_2.isEnabled()) {
            new AlertView("提示", "确定提交审核吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                @Override
                public void onItemClick(Object o, int position) {
                    if (position == 0) {
                        if (irModelFieldsOne2Many != null) {
                            if (irModelFieldsOne2Many.getRequired() && bodyList.size() == 0) {
                                ToastUtils.showShortToast("表体内容必须填写");
                                return;
                            }
                        }
                        if (!saveHeaderData()) {
                            return;
                        }
                        HashMap<String, Object> param = new HashMap<>();
                        param.put("header", JSON.toJSONString(headerItem));
                        param.put("body", JSON.toJSONString(bodyList));
                        param.put("entryDeleteItems", JSON.toJSONString(entryDeleteItems));
                        param.put("bodyUpdateList", JSON.toJSONString(bodyUpdateList));
                        param.put("model_id", intent.getLongExtra("model_id", 0));
                        param.put("action", intent.getStringExtra("action"));
                        param.put("check", "check");
                        HttpRequest httpRequest = new HttpRequest(mContext, WebApi.api(), "postForm", JSON.toJSONString(param), true, true);
                        httpRequest.send(new SimpleHttpListener<JSONObject>() {
                            @Override
                            public void onSucceed(int what, Response<JSONObject> response) {
                                super.onSucceed(what, response);
                                ToastUtils.showShortToast("审核成功");
                                setResult(RESULT_OK, getIntent());
                                finish();
                            }
                        });
                    }
                }
            }).show();
        }
    }

    //反审核
    @OnClick(R.id.btn_3)
    public void f3() {
        if (btn_3.isEnabled()) {
            new AlertView("提示", "确定提交反审核吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                @Override
                public void onItemClick(Object o, int position) {
                    if (position == 0) {
                        HashMap<String, Object> param = new HashMap<>();
                        param.put("key_value", intent.getStringExtra(intent.getStringExtra("key_name")));
                        param.put("key_name", intent.getStringExtra("key_name"));
                        param.put("model_id", intent.getLongExtra("model_id", 0));
                        param.put("check", "uncheck");
                        HttpRequest httpRequest = new HttpRequest(mContext, WebApi.api(), "postCheck", JSON.toJSONString(param), true, true);
                        httpRequest.setmWhat(-3);
                        httpRequest.send(new SimpleHttpListener<JSONObject>() {
                            @Override
                            public void onSucceed(int what, Response<JSONObject> response) {
                                super.onSucceed(what, response);
                                if (what == -3) {
                                    ToastUtils.showShortToast("反审核成功");
                                    setResult(RESULT_OK, getIntent());
                                    finish();
                                }
                            }
                        });
                    }
                }
            }).show();
        }
    }

    //保存表格数据
    @OnClick(R.id.btn_4)
    public void f4() {
        if (irModelFieldsOne2ManyList != null && btn_4.isEnabled()) {
            KeyboardUtils.hideSoftInput(this);
            //保存one2many字段的数据
            final ArrayList<String> item = new ArrayList<>();
            final HashMap<String, Object> map = new HashMap<>();
            final HashMap<String, Object> bodyMap = new HashMap<>(bodyItem);
            boolean cancel = false; //检查是否必填的判断
            String msg = ""; //提示信息
            boolean compute = false; //是否有计算字段
            final ArrayList<HashMap<String, Object>> computeFields = new ArrayList<>();
            for (int i = 0; i < irModelFieldsOne2ManyList.size(); i++) {
                IrModelFields field = irModelFieldsOne2ManyList.get(i);
                if (field.getVisiable()) {
                    AutoCompleteTextView actv = (AutoCompleteTextView) itemWidget.get(field.getId());
                    String value = actv.getText().toString();
                    if (field.getRequired()) {
                        if (value.equals("")) {
                            cancel = true;
                            msg = "表体 " + field.getField_desc() + " 必须填写，保存失败";
                            break;
                        } else if (bodyMap.get(field.getName()) == null) {
                            cancel = true;
                            msg = "表体 " + field.getField_desc() + "：" + value + " 不存在，保存失败";
                            break;
                        }
                    }
                    item.add(value);
                    map.put(field.getName(), value);
                } else {
                    if (curRow == -1 && TextUtils.isEmpty(field.getRel_change_field())) {
                        bodyMap.put(field.getName(), setDefValue(field.getDef_value(), field, 1));
                    }
                }
                if (field.getTcompute()) {
                    HashMap<String, Object> m = new HashMap<>();
                    m.put("name", field.getName());
                    m.put("index", item.size() - 1);
                    computeFields.add(m);
                    compute = true;
                }
            }
            if (cancel) {
                ToastUtils.showLongToast(msg);
            } else {
                //有需要计算的字段
                if (compute) {
                    HashMap<String, Object> param = new HashMap<>();
                    param.put("bodyItem", JSON.toJSONString(bodyMap));
                    param.put("model_id", irModelFieldsOne2Many.getRelation_model_id());
                    HttpRequest httpRequest = new HttpRequest(mContext, WebApi.api(), "getCompute", JSON.toJSONString(param), true, true);
                    httpRequest.setmWhat(-10);
                    httpRequest.send(new SimpleHttpListener<JSONObject>() {
                        @Override
                        public void onSucceed(int what, Response<JSONObject> response) {
                            super.onSucceed(what, response);
                            if (what == -10) {
                                JSONObject data = response.get().optJSONObject("data");
                                for (int i = 0; i < computeFields.size(); i++) {
                                    String fieldname = String.valueOf(computeFields.get(i).get("name"));
                                    bodyMap.put(fieldname, data.optString(fieldname));
                                    map.put(fieldname, data.optString(fieldname));
                                    item.set((Integer) computeFields.get(i).get("index"), StringUtils.formatNumber(data.optString(fieldname)));
                                }
                                if (curRow > -1) {
                                    //有修改行
                                    tableListData.set(curRow + 1, item);
                                    mList.set(curRow, map);
                                    bodyList.set(curRow, bodyMap);
                                    if (bodyMap.get(irModelFieldsOne2ManyKey.getName()) != null) {
                                        if (!bodyUpdateList.contains(String.valueOf(bodyMap.get(irModelFieldsOne2ManyKey.getName()))))
                                            bodyUpdateList.add(String.valueOf(bodyMap.get(irModelFieldsOne2ManyKey.getName())));
                                    }
                                } else {
                                    if (irModelAccessOne2Many != null && irModelAccessOne2Many.getPerm_create()) {
                                        tableListData.add(1, item);
                                        mList.add(0, map);
                                        bodyList.add(0, bodyMap);
                                    } else {
                                        ToastUtils.showLongToast("表体无创建权限");
                                    }
                                }
                                tableDataAdapter = new TableDataAdapter(mContext, tableListData, 28, 14);
                                table.setAdapter(tableDataAdapter);
                                cleanBodyForm();
                            }
                        }
                    });
                } else {
                    if (curRow > -1) {
                        //有修改行
                        tableListData.set(curRow + 1, item);
                        mList.set(curRow, map);
                        bodyList.set(curRow, bodyMap);
                        if (bodyMap.get(irModelFieldsOne2ManyKey.getName()) != null) {
                            if (!bodyUpdateList.contains(String.valueOf(bodyMap.get(irModelFieldsOne2ManyKey.getName()))))
                                bodyUpdateList.add(String.valueOf(bodyMap.get(irModelFieldsOne2ManyKey.getName())));
                        }
                    } else {
                        if (irModelAccessOne2Many != null && irModelAccessOne2Many.getPerm_create()) {
                            tableListData.add(1, item);
                            mList.add(0, map);
                            bodyList.add(0, bodyMap);
                        } else {
                            ToastUtils.showShortToast("表体无创建权限");
                        }
                    }
                    tableDataAdapter = new TableDataAdapter(mContext, tableListData, 28, 14);
                    table.setAdapter(tableDataAdapter);
                    cleanBodyForm();
                }
                notSave = true;
            }
        }
    }

    //清除表体内容
    private void cleanBodyForm() {
        KeyboardUtils.hideSoftInput(this);
        bodyItem = new HashMap<>();
        curRow = -1;
        cleanScanLog(1);
        for (int i = 0; i < irModelFieldsOne2ManyList.size(); i++) {
            IrModelFields field = irModelFieldsOne2ManyList.get(i);
            if (field.getVisiable()) {
                AutoCompleteTextView actv = (AutoCompleteTextView) itemWidget.get(field.getId());
                actv.setText(setDefValue(field.getDef_value(), field, 1));
            }
        }
    }

    //保存表头数据
    private boolean saveHeaderData() {
        boolean result = true;
        for (int i = 0; i < irModelFieldsList.size(); i++) {
            IrModelFields field = irModelFieldsList.get(i);

            if (field.getVisiable()) {
                AutoCompleteTextView actv = (AutoCompleteTextView) itemWidget.get(field.getId());
                String value = actv.getText().toString();
                if (field.getRequired() && value.equals("")) {
                    ToastUtils.showLongToast("表头 " + field.getField_desc() + " 必须输入");
                    result = false;
                    break;
                }
                headerShowMap.put(field.getName(), value);
            } else {
                if (intent.getStringExtra("action").equals("create") && TextUtils.isEmpty(field.getRel_change_field())) {
                    headerItem.put(field.getName(), setDefValue(field.getDef_value(), field, 0));
                }
            }

            //移除不保存的字段
            if (!field.getStore()) {
                headerItem.remove(field.getName());
            }
        }
        return result;
    }

    @OnClick(R.id.ib_submit)
    public void submit() {
        new AlertView("提示", "确定提交吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
                    if (irModelFieldsOne2Many != null) {
                        if (irModelFieldsOne2Many.getRequired() && bodyList.size() == 0) {
                            ToastUtils.showLongToast("表体内容必须填写");
                            return;
                        }
                    }
                    if (!saveHeaderData()) {
                        return;
                    }
                    //移除不需要保存的字段
                    if (bodyList.size() > 0) {
                        for (int i = 0; i < bodyList.size(); i++) {
                            for (int j = 0; j < irModelFieldsOne2ManyList.size(); j++) {
                                if (!irModelFieldsOne2ManyList.get(j).getStore()) {
                                    bodyList.get(i).remove(irModelFieldsOne2ManyList.get(j).getName());
                                }
                            }
                        }
                    }

                    HashMap<String, Object> param = new HashMap<>();
                    param.put("header", JSON.toJSONString(headerItem));
                    param.put("body", JSON.toJSONString(bodyList));
                    param.put("entryDeleteItems", JSON.toJSONString(entryDeleteItems));
                    param.put("bodyUpdateList", JSON.toJSONString(bodyUpdateList));
                    param.put("model_id", intent.getLongExtra("model_id", 0));
                    param.put("action", intent.getStringExtra("action"));
                    HttpRequest httpRequest = new HttpRequest(mContext, WebApi.api(), "postForm", JSON.toJSONString(param), true, true);
                    httpRequest.setmWhat(-2);
                    httpRequest.send(new SimpleHttpListener<JSONObject>() {
                        @Override
                        public void onSucceed(int what, Response<JSONObject> response) {
                            super.onSucceed(what, response);
                            if (what == -2) {
                                ToastUtils.showShortToast("提交成功");
                                setResult(RESULT_OK, intent);
                                finish();
                            }
                        }
                    });
                }
            }
        }).show();
    }

    //实体键启动扫描
    private void buttonScan() {
        if (sv_wrap.getVisibility() == View.GONE) {
            if (scanBodyLog.size() > 0) {
                curFieldId = (long) scanBodyLog.get(0).get("field_id");
                for (int i = 0; i < scanBodyLog.size(); i++) {
                    if (!(boolean) scanBodyLog.get(i).get("scan")) {
                        curFieldId = (long) scanBodyLog.get(i).get("field_id");
                        break;
                    }
                }
                openScan();
            }
        } else {
            if (scanHeaderLog.size() > 0) {
                curFieldId = (long) scanHeaderLog.get(0).get("field_id");
                for (int i = 0; i < scanHeaderLog.size(); i++) {
                    if (!(boolean) scanHeaderLog.get(i).get("scan")) {
                        curFieldId = (long) scanHeaderLog.get(i).get("field_id");
                        break;
                    }
                }
                openScan();
            }
        }
    }

    //保存选单数据
    private void saveChoiceData(String choice_data, String choice_data_keys) {
        com.alibaba.fastjson.JSONArray data = JSON.parseArray(choice_data);
        com.alibaba.fastjson.JSONArray keys = JSON.parseArray(choice_data_keys);

        ToastUtils.showLongToast(data.toString());
        if (irModelFieldsOne2Many != null && irModelFieldsOne2ManyList.size() > 0) {

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 131 && event.getRepeatCount() == 0) {
            f1();
            return false;
        } else if (keyCode == 132 && event.getRepeatCount() == 0) {
            f2();
            return false;
        } else if (keyCode == 133 && event.getRepeatCount() == 0) {
            f3();
            return false;
        } else if (keyCode == 134 && event.getRepeatCount() == 0) {
            f4();
            return false;
        } else if (keyCode == 139 && event.getRepeatCount() == 0) {
            buttonScan();
            return false;
        } else if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (notSave) {
                back();
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    //后退提示
    private void back() {
        new AlertView("提示", "有数据未保存，确定退出本页吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new com.aihook.alertview.library.OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
                    finish();
                }
            }
        }).show();
    }

    /**
     * 检查相机权限
     */
    private void checkCameraPermission() {
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
            openScan();
        } else {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                ToastUtils.showLongToast("请授权，否则无法扫描");
            }
            //申请权限。
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 100);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //android6.0权限检查，重新启动扫描
        if (requestCode == 100) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openScan();
            } else {
                ToastUtils.showShortToast("拒绝授权");
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUESTCODE_CAMERA && resultCode == RESULT_OK && data != null) {
            //扫码结果
            getScanResult(data.getStringExtra("result"));
        } else if (requestCode == CHOICEBILL && resultCode == RESULT_OK && data != null) {
            //选单处理结果
            saveChoiceData(data.getStringExtra("choice_data"), data.getStringExtra("choice_data_keys"));
        }
    }

    @Override
    protected void onDestroy() {
        irModelFieldsOne2Many = null;
        if (irModelFieldsOne2ManyList != null)
            irModelFieldsOne2ManyList.clear();
        irModelAccessOne2Many = null;
        irModelFieldsOne2ManyKey = null;
        if (entryDeleteItems != null)
            entryDeleteItems.clear();
        irActWindow = null;
        if (irModelFieldsList != null)
            irModelFieldsList.clear();
        if (fieldsMap != null)
            fieldsMap.clear();
        if (tableListData != null)
            tableListData.clear();
        if (scanHeaderLog != null)
            scanHeaderLog.clear();
        if (scanBodyLog != null)
            scanBodyLog.clear();
        if (headerShowMap != null)
            headerShowMap.clear();
        if (mList != null)
            mList.clear();
        bodyList.clear();
        if (itemWidget != null)
            itemWidget.clear();
        if (many2oneListMap != null)
            many2oneListMap.clear();
        if (many2oneList != null)
            many2oneList.clear();
        if (many2oneMoreListMap != null)
            many2oneMoreListMap.clear();
        if (changeMap != null)
            changeMap.clear();
        if (changeSelectList != null)
            changeSelectList.clear();
        if (many2oneMoreList != null)
            many2oneMoreList.clear();
        if (bodyItem != null)
            bodyItem.clear();
        if (headerItem != null)
            headerItem.clear();
        bodyUpdateList.clear();
        if (selectList != null)
            selectList.clear();
        if (many2oneFieldHashMap != null)
            many2oneFieldHashMap.clear();
        if (many2oneDefValue != null)
            many2oneDefValue.clear();
        if (many2oneOriginMore != null)
            many2oneOriginMore.clear();
        super.onDestroy();
    }

    /**
     * 获取通过接口设置的默认值
     */
    private void getApiDefault() {
        HashMap<String, Object> param = new HashMap<>();
        param.put("model_id", model_id);
        HttpRequest httpRequest = new HttpRequest(mContext, WebApi.api(), "getApiDefault", JSON.toJSONString(param), true, true);
        httpRequest.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onFailed(int what, Response<JSONObject> response) {
                super.onFailed(what, response);
                ToastUtils.showLongToast("获取默认值失败，请重新打开单据");
                finish();
            }

            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                super.onSucceed(what, response);
                JSONObject data = response.get().optJSONObject("data");
                //表头
                if (intent.getStringExtra("action").equals("create")) {
                    for (int i = 0; i < irModelFieldsList.size(); i++) {
                        IrModelFields irModelFields = irModelFieldsList.get(i);
                        if (irModelFields.getDef_value().indexOf("api_") > -1 && irModelFields.getDef_value().indexOf("_api") > -1) {
                            irModelFields.setDef_value(data.optString(String.valueOf(irModelFields.getId())));
                            if (irModelFields.getVisiable()) {
                                AutoCompleteTextView actv = (AutoCompleteTextView) itemWidget.get(irModelFields.getId());
                                actv.setText(data.optString(String.valueOf(irModelFields.getId())));
                            } else {
                                headerItem.put(irModelFields.getName(), data.optString(String.valueOf(irModelFields.getId())));
                            }
                        } else if (irModelFields.getTtype().equals("many2one") && !irModelFields.getDef_value().equals("")) {
                            many2oneDefValue.put(irModelFields.getId(), data.optString(String.valueOf(irModelFields.getId())));
                            headerItem.put(irModelFields.getName(), data.optString(String.valueOf(irModelFields.getId())));
                        }
                    }
                }
                //表体
                if (irModelFieldsOne2ManyList != null) {
                    for (int i = 0; i < irModelFieldsOne2ManyList.size(); i++) {
                        IrModelFields irModelFields = irModelFieldsOne2ManyList.get(i);
                        if (irModelFields.getDef_value().indexOf("api_") > -1 && irModelFields.getDef_value().indexOf("_api") > -1) {
                            irModelFields.setDef_value(data.optString(String.valueOf(irModelFields.getId())));
                            if (irModelFields.getVisiable()) {
                                AutoCompleteTextView actv = (AutoCompleteTextView) itemWidget.get(irModelFields.getId());
                                actv.setText(data.optString(String.valueOf(irModelFields.getId())));
                            } else {
                                bodyItem.put(irModelFields.getName(), data.optString(String.valueOf(irModelFields.getId())));
                            }
                        } else if (irModelFields.getTtype().equals("many2one") && !irModelFields.getDef_value().equals("")) {
                            many2oneDefValue.put(irModelFields.getId(), data.optString(String.valueOf(irModelFields.getId())));
                            bodyItem.put(irModelFields.getName(), data.optString(String.valueOf(irModelFields.getId())));
                        }
                    }
                }
            }
        });
    }
}
